// WeChat JS SDK config helper
// ===========================

define(['zepto', 'ctx', 'wx'], function($, ctx, wx) {
	return {
		requestJsconfig: function() {
			var defer = $.Deferred()
			var url = window.location.href.split("#")[0]
			$.getJSON(ctx.host + "jsconfig?curl=" + url, function(response) {
				if (response.code === '0') {
					defer.resolve(response.data.jsconfig)
				} else {
					console.error(response.messgae)
				}
			})
			return defer.promise()
		},
		
		config: function() {
			// Check debug option
			var debug = location.search.indexOf('debug=true') > -1
			// Slice all arguments into array
			var apis = Array.prototype.slice.call(arguments)
			// Fetch js config from api
			var fetchingJsconfig = this.requestJsconfig()
			$.when(fetchingJsconfig).done(function(jsconfig) {
				wx.config({
					debug: debug,
					appId: jsconfig.appid, 
					timestamp: jsconfig.timestamp , 
					nonceStr: jsconfig.nonceStr, 
					signature: jsconfig.signature,
					jsApiList: apis
				})
			})	
		}
	}
})